package l1j.server.server.clientpackets;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.SimpleDateFormat;//TODO 角色誕生by99團隊

import l1j.opqlo.Server.L1World.WorldClan;
import l1j.server.Config;
import l1j.server.DatabaseFactory;
import l1j.server.echo.ClientThread;
import l1j.server.server.datatables.CharObjidTable;
import l1j.server.server.datatables.CharacterTable;
import l1j.server.server.model.L1Clan;
import l1j.server.server.serverpackets.S_CharAmount;
import l1j.server.server.serverpackets.S_CharPacks;
import l1j.server.server.utils.SQLUtil;

public class C_CommonClick extends ClientBasePacket {
	private static final String C_COMMON_CLICK = "[C] C_CommonClick";

	private static Logger _log = Logger.getLogger(C_CommonClick.class.getName());

	private void deleteCharacter(ClientThread client) {
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {

			conn = DatabaseFactory.get().getConnection();
			pstm = conn.prepareStatement("SELECT * FROM characters WHERE account_name=? ORDER BY objid");
			pstm.setString(1, client.getAccountName());
			rs = pstm.executeQuery();

			while (rs.next()) {
				final String name = rs.getString("char_name");
				final String clanname = rs.getString("Clanname");

				final Timestamp deleteTime = rs.getTimestamp("DeleteTime");
				if (deleteTime != null) {
					final Calendar cal = Calendar.getInstance();
					final long checkDeleteTime = (cal.getTimeInMillis() - deleteTime.getTime()) / 1000 / 3600;
					if (checkDeleteTime >= 0) {
						final L1Clan clan = WorldClan.get().getClan(clanname);
						if (clan != null) {
							clan.delMemberName(name);
						}
						// 已創人物數量
						final int countCharacters = client.getAccount().get_countCharacters();
						client.getAccount().set_countCharacters(countCharacters - 1);
						// 移出已用名稱清單
						CharObjidTable.get().charRemove(name);

						CharacterTable.getInstance().deleteCharacter(client.getAccountName(), name);
					}
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(conn);
		}
	}

	@Override
	public String getType() {
		return C_COMMON_CLICK;
	}

	private void sendCharPacks(ClientThread client) {
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {

			conn = DatabaseFactory.get().getConnection();
			pstm = conn.prepareStatement("SELECT * FROM characters WHERE account_name=? ORDER BY objid");
			pstm.setString(1, client.getAccountName());
			rs = pstm.executeQuery();

			while (rs.next()) {
				final String name = rs.getString("char_name");
				final String clanname = rs.getString("Clanname");
				final int type = rs.getInt("Type");
				final byte sex = rs.getByte("Sex");
				final int lawful = rs.getInt("Lawful");

				int currenthp = rs.getInt("CurHp");
				currenthp = Math.max(currenthp, 1);
				currenthp = Math.min(currenthp, 32767);

				int currentmp = rs.getInt("CurMp");
				currentmp = Math.max(currentmp, 1);
				currentmp = Math.min(currentmp, 32767);

				int lvl= 1;
				if (Config.CHARACTER_CONFIG_IN_SERVER_SIDE) {
					lvl = rs.getInt("level");
					lvl= Math.max(lvl, 1);
					lvl= Math.min(lvl, 127);
				}

				//opqlo 七屬性破127
				final int ac = rs.getShort("Ac");
				int str = rs.getShort("Str");
				str = Math.max(str, 1);
				str = Math.min(str, 255);

				int dex = rs.getShort("Dex");
				dex = Math.max(dex, 1);
				dex = Math.min(dex, 255);

				int con = rs.getShort("Con");

				con = Math.max(con, 1);
				con = Math.min(con, 255);

				int wis = rs.getShort("Wis");
				wis = Math.max(wis, 1);
				wis = Math.min(wis, 255);

				int cha = rs.getShort("Cha");
				cha = Math.max(cha, 1);
				cha = Math.min(cha,255);

				int intel = rs.getShort("Intel");
				intel = Math.max(intel, 1);
				intel = Math.min(intel, 255);

				//opqlo 七屬性破127
				final int accessLevel = rs.getShort("AccessLevel");
				//TODO 角色誕生by99團隊
				final Timestamp _birthday = rs.getTimestamp("birthday");
				final SimpleDateFormat SimpleDate = new SimpleDateFormat("yyyyMMdd");
				final int birthday = Integer.parseInt(SimpleDate.format(_birthday.getTime()));
				//TODO 角色誕生by99團隊
				final S_CharPacks cpk = new S_CharPacks(name, clanname, type, sex,
						lawful, currenthp, currentmp, ac, lvl, str, dex, con,
						wis, cha, intel, accessLevel, birthday);

				client.out().encrypt(cpk);
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(conn);
		}
	}

	@Override
	public void start(final byte[] decrypt, final ClientThread client) {
		try {
			// 資料載入
//			this.read(decrypt);

			this.deleteCharacter(client); // 指定人物刪除時間抵達 執行人物刪除

			final int amountOfChars = client.getAccount().get_countCharacters();

			client.out().encrypt(new S_CharAmount(amountOfChars, client));

			if (amountOfChars > 0) {
				this.sendCharPacks(client);
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);

		} finally {
			this.over();
		}
	}
}